package cn.bugstack.ai.config;

import cn.bugstack.ai.handler.AIWebSocketHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.*;

/**
 * WebSocket 配置类
 * 
 * @author bugstack
 */
@Slf4j
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    private final AIWebSocketHandler aiWebSocketHandler;
    
    @Value("${spring.websocket.allowed-origins:*}")
    private String allowedOrigins;

    public WebSocketConfig(AIWebSocketHandler aiWebSocketHandler) {
        this.aiWebSocketHandler = aiWebSocketHandler;
        log.info("✅ WebSocketConfig initialized");
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        log.info("📝 Registering WebSocket handlers...");
        log.info("   - Endpoint: /ws/ai");
        log.info("   - Allowed origins: {}", allowedOrigins);
        
        registry
                // 注册 WebSocket 处理器
                .addHandler(aiWebSocketHandler, "/ws/ai")
                // 设置允许的跨域来源
                .setAllowedOrigins(allowedOrigins.split(","))
                // 启用 SockJS 降级支持（兼容不支持 WebSocket 的浏览器）
                .withSockJS()
                    // 设置 SockJS 客户端库的 URL（可选）
                    .setClientLibraryUrl("https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js")
                    // 设置心跳间隔（毫秒）
                    .setHeartbeatTime(25000);
        
        log.info("✅ WebSocket handlers registered successfully");
    }
}
